#include "led_manager.h"
#include "pin_config.h"

LEDManager::LEDManager(uint8_t statusPin, uint8_t stripPin, uint16_t ledCount) 
  : statusLedPin(statusPin), ws2812Pin(stripPin), numLeds(ledCount),
    currentStatus(LED_OFF), currentEffect(EFFECT_BREATH), lastUpdate(0), blinkInterval(500), 
    ledState(false), breathValue(0), breathDirection(true),
    ws2812Enabled(true), statusLedEnabled(true), globalBrightness(200),
    rainbowOffset(0), meteorPos(0), theaterStep(0),
    drawingEffectMode(EFFECT_BREATH), drawingBrightness(180), drawingSpeed(5), 
    drawingEffectInterval(100), drawingSessionActive(false),
    temporaryColorActive(false), temporaryColor(0, 0, 0), temporaryBrightness(255),
    currentTheta(0.0f), currentRho(0.0f), fireHeat(nullptr) {
  
  // 动态分配火焰效果数组 - 优化内存使用
  if (numLeds > 0) {
    fireHeat = new uint8_t[numLeds];
    for (int i = 0; i < numLeds; i++) {
      fireHeat[i] = 0;
    }
  }
  
  // 初始化颜色方案 - 更加丰富的配色
  colorOff = LEDColor(0, 0, 0);
  colorStartup = LEDColor(255, 255, 255);      // 白色 - 启动
  colorInitializing = LEDColor(255, 200, 100); // 暖白色 - 初始化中
  colorWifiConnecting = LEDColor(0, 100, 255); // 深蓝色 - WiFi连接中
  colorWifiConnected = LEDColor(0, 255, 100);  // 青绿色 - WiFi已连接
  colorWifiFailed = LEDColor(255, 50, 0);      // 橙红色 - WiFi失败
  colorIdle = LEDColor(100, 255, 200);         // 浅青色 - 待机
  colorHoming = LEDColor(255, 200, 0);         // 金黄色 - 归零中
  colorDrawing = LEDColor(50, 150, 255);       // 天蓝色 - 绘图中
  colorPaused = LEDColor(255, 100, 50);        // 橙色 - 暂停
  colorCompleted = LEDColor(100, 255, 100);    // 亮绿色 - 完成
  colorError = LEDColor(255, 0, 100);          // 粉红色 - 错误
  colorEmergency = LEDColor(255, 0, 255);      // 紫色 - 紧急停止
  
  // 初始化绘图专用颜色和效果
  drawingColor = colorDrawing;
  drawingEffectMode = EFFECT_BREATH;  // 🔧 修复：设置默认绘图效果为呼吸效果
  drawingBrightness = 180;           // 🔧 修复：使用与构造函数一致的亮度值
  drawingSpeed = 5;                  // 默认绘图效果速度（中等）
  drawingEffectInterval = 20;        // 🔧 修复：使用更快的间隔匹配breathEffect的20ms更新频率
  drawingSessionActive = false;      // 初始化绘图会话状态
  
  strip = nullptr;
}

LEDManager::~LEDManager() {
  if (strip) {
    delete strip;
  }
  if (fireHeat) {
    delete[] fireHeat;
  }
}

void LEDManager::setGlobalBrightness(uint8_t brightness) {
  globalBrightness = brightness;
  if (strip && ws2812Enabled) {
    strip->setBrightness(globalBrightness);
    strip->show();
  }
  Serial.printf("💡 全局亮度设置为: %d%% (%d/255)\n", (brightness * 100) / 255, brightness);
}

// ==================== 绘图专用灯光效果设置 ====================

void LEDManager::setDrawingEffect(LEDEffectMode mode, LEDColor color) {
  drawingEffectMode = mode;
  drawingColor = color;
  drawingEffectInterval = map(drawingSpeed, 1, 10, 200, 20);  // 速度越快间隔越短
  
  Serial.printf("🎨 绘图灯光效果设置 - 模式: %d, 颜色: RGB(%d,%d,%d)\n", 
                mode, color.r, color.g, color.b);
}

void LEDManager::setDrawingBrightness(uint8_t brightness) {
  drawingBrightness = brightness;
  Serial.printf("🎨 绘图亮度设置为: %d%% (%d/255)\n", (brightness * 100) / 255, brightness);
}

void LEDManager::setDrawingSpeed(uint8_t speed) {
  drawingSpeed = constrain(speed, 1, 10);
  drawingEffectInterval = map(drawingSpeed, 1, 10, 200, 20);  // 重新计算间隔
  Serial.printf("🎨 绘图效果速度设置为: %d (间隔: %dms)\n", drawingSpeed, drawingEffectInterval);
}

void LEDManager::updateDrawingEffects() {
  unsigned long currentTime = millis();
  static unsigned long lastDrawingUpdate = 0;
  static unsigned long lastDebugOutput = 0;
  
  // 🔧 修复：极坐标追踪效果需要实时更新，其他效果才需要时间间隔限制
  if (drawingEffectMode != EFFECT_POLAR_TRACK && currentTime - lastDrawingUpdate < drawingEffectInterval) {
    return;  // 还没到更新时间（除了极坐标追踪）
  }
  lastDrawingUpdate = currentTime;
  
  // 🔧 调试：每5秒输出一次绘图效果状态
  // if (currentTime - lastDebugOutput > 5000) {
  //   Serial.printf("🎨 绘图效果调试: 模式=%d, 颜色=RGB(%d,%d,%d), 亮度=%d, 间隔=%dms\n", 
  //                 drawingEffectMode, drawingColor.r, drawingColor.g, drawingColor.b, 
  //                 drawingBrightness, drawingEffectInterval);
  //   lastDebugOutput = currentTime;
  // }
  
  switch (drawingEffectMode) {
    case EFFECT_SOLID:
      solidEffect(drawingColor);
      break;
    case EFFECT_BREATH:
      breathEffect(drawingColor);
      break;
    case EFFECT_BLINK:
      blinkEffect(drawingColor, drawingEffectInterval * 2);
      break;
    case EFFECT_RAINBOW:
      rainbowEffect();
      break;
    case EFFECT_FIRE:
      fireEffect();
      break;
    case EFFECT_WAVE:
      waveEffect(drawingColor);
      break;
    case EFFECT_METEOR:
      meteorEffect(drawingColor);
      break;
    case EFFECT_PROGRESS:
      solidEffect(drawingColor);  // 进度条效果由外部调用setProgress处理
      break;
    case EFFECT_SPARKLE:
      sparkleEffect(drawingColor);
      break;
    case EFFECT_THEATER_CHASE:
      theaterChaseEffect(drawingColor);
      break;
    case EFFECT_POLAR_TRACK:
      polarTrackEffect(drawingColor);
      break;
  }
}

// ==================== 绘图专用效果方法 ====================

// 注意：drawingBreathEffect 和 drawingBlinkEffect 已移除，
// 统一使用 breathEffect 和 blinkEffect 来避免代码重复

// ==================== 绘图会话管理 ====================

void LEDManager::startDrawingSession() {
  // 🔧 重构：纯硬件层，只管理标志位，不处理业务逻辑
  drawingSessionActive = true;
  Serial.println("🔧 LED硬件层：绘图会话标志已设置");
}

void LEDManager::endDrawingSession() {
  // 🔧 重构：纯硬件层，只管理标志位，不处理业务逻辑
  drawingSessionActive = false;
  Serial.println("🔧 LED硬件层：绘图会话标志已清除");
}

void LEDManager::begin() {
  // 初始化状态LED
  if (statusLedEnabled) {
    pinMode(statusLedPin, OUTPUT);
    digitalWrite(statusLedPin, LOW);
  }
  
  // 初始化WS2812灯带
  if (ws2812Enabled) {
    strip = new Adafruit_NeoPixel(numLeds, ws2812Pin, NEO_GRB + NEO_KHZ800);
    strip->begin();
    strip->setBrightness(globalBrightness);
    strip->clear();
    strip->show();
  }
  
  Serial.printf("💡 LED管理器初始化完成 - 状态LED: %s, WS2812: %s, 灯珠数: %d, 亮度: %d%%\n", 
                statusLedEnabled ? "启用" : "禁用",
                ws2812Enabled ? "启用" : "禁用",
                numLeds, (globalBrightness * 100) / 255);
  
  // 显示颜色配置
  Serial.println("🎨 LED颜色配置:");
  Serial.printf("  空闲: RGB(%d,%d,%d) - 浅青色\n", colorIdle.r, colorIdle.g, colorIdle.b);
  Serial.printf("  绘图: RGB(%d,%d,%d) - 天蓝色\n", colorDrawing.r, colorDrawing.g, colorDrawing.b);
  Serial.printf("  暂停: RGB(%d,%d,%d) - 橙色\n", colorPaused.r, colorPaused.g, colorPaused.b);
  Serial.printf("  错误: RGB(%d,%d,%d) - 粉红色\n", colorError.r, colorError.g, colorError.b);
  
  // 启动测试
  setStatus(LED_STARTUP);
}

void LEDManager::update() {
  // 🔧 调试：确认update函数被调用（增加频率以便调试）
  static unsigned long lastUpdateDebug = 0;
  
  if (!ws2812Enabled && !statusLedEnabled) return;
  
  unsigned long currentTime = millis();
  
  // 根据当前状态选择效果和颜色
  LEDColor statusColor;
  LEDEffectMode effectMode = currentEffect;
  
  switch (currentStatus) {
    case LED_OFF:
      if (statusLedEnabled) digitalWrite(statusLedPin, LOW);
      if (ws2812Enabled) setStripColor(colorOff);
      return;
      
    case LED_STARTUP:
      // 🔧 修复：移除自动状态切换，交给LEDControlCenter管理
      statusColor = colorStartup;
      effectMode = EFFECT_THEATER_CHASE;
      break;
      
    case LED_INITIALIZING:
      statusColor = colorInitializing;
      effectMode = EFFECT_BREATH;
      break;
      
    case LED_WIFI_CONNECTING:
      statusColor = colorWifiConnecting;
      effectMode = EFFECT_BREATH;
      break;
      
    case LED_WIFI_CONNECTED:
      statusColor = colorWifiConnected;
      effectMode = EFFECT_SPARKLE;
      if (statusLedEnabled) digitalWrite(statusLedPin, LOW);  // 状态LED熄灭表示正常
      break;
      
    case LED_WIFI_FAILED:
      statusColor = colorWifiFailed;
      effectMode = EFFECT_BLINK;
      break;
      
    case LED_IDLE:
      statusColor = colorIdle;
      effectMode = EFFECT_WAVE;
      break;
      
    case LED_HOMING:
      statusColor = colorHoming;
      effectMode = EFFECT_METEOR;
      break;
      
    case LED_DRAWING:
      statusColor = drawingColor;  // 使用用户设置的绘图颜色
      effectMode = drawingEffectMode;  // 使用用户设置的绘图效果
      if (statusLedEnabled) digitalWrite(statusLedPin, HIGH);
      break;
      
    case LED_PAUSED:
      statusColor = colorPaused;
      effectMode = EFFECT_RAINBOW;  // 🔧 修改：暂停时显示彩虹效果
      break;
      
    case LED_COMPLETED:
      // 🔧 修复：移除自动状态切换，交给LEDControlCenter管理
      statusColor = colorCompleted;
      effectMode = EFFECT_RAINBOW;  // 保持彩虹效果
      if (statusLedEnabled) digitalWrite(statusLedPin, HIGH);
      break;
      
    case LED_ERROR:
      statusColor = colorError;
      effectMode = EFFECT_BLINK;
      break;
      
    case LED_EMERGENCY:
      statusColor = colorEmergency;
      effectMode = EFFECT_BLINK;
      break;
  }
  

  
  // 执行对应的效果
  if (ws2812Enabled && strip) {
    // � 修复：优先检查临时颜色状态，但确保正确的亮度处理
    if (temporaryColorActive) {
      // 显示临时颜色（用于按键反馈）
      uint8_t adjustedBrightness = (temporaryBrightness * globalBrightness) / 255;
      setStripColor(temporaryColor, adjustedBrightness);
      if (statusLedEnabled) {
        digitalWrite(statusLedPin, adjustedBrightness > 64 ? HIGH : LOW);
      }
      return;
    }
    
    // 🔧 修复：只有真正的绘图状态才使用绘图效果，暂停和完成状态使用标准效果
    if (currentStatus == LED_DRAWING) {
      // 🔧 调试：确认绘图状态被处理（减少输出频率）
      static unsigned long lastDrawingDebug = 0;
      if (millis() - lastDrawingDebug > 30000) { // 每30秒最多打印一次
        Serial.println("🎨 确认：正在处理LED_DRAWING状态");
        lastDrawingDebug = millis();
      }
      updateDrawingEffects();
    } else {
      switch (effectMode) {
        case EFFECT_SOLID:
          solidEffect(statusColor);
          break;
        case EFFECT_BREATH:
          breathEffect(statusColor);
          break;
        case EFFECT_BLINK:
          blinkEffect(statusColor, 500);
          break;
        case EFFECT_RAINBOW:
          rainbowEffect();
          break;
        case EFFECT_FIRE:
          fireEffect();
          break;
        case EFFECT_WAVE:
          waveEffect(statusColor);
          break;
        case EFFECT_METEOR:
          meteorEffect(statusColor);
          break;
        case EFFECT_PROGRESS:
          // 进度条效果在 setProgress 中单独处理
          solidEffect(statusColor);
          break;
        case EFFECT_SPARKLE:
          sparkleEffect(statusColor);
          break;
        case EFFECT_THEATER_CHASE:
          theaterChaseEffect(statusColor);
          break;
        case EFFECT_POLAR_TRACK:
          polarTrackEffect(statusColor);
          break;
      }
    }
  }
}

const char* LEDManager::getStatusName(LEDStatus status) {
  static const char* statusNames[] = {"OFF", "STARTUP", "INITIALIZING", "WIFI_CONNECTING", 
                                     "WIFI_CONNECTED", "WIFI_FAILED", "IDLE", "HOMING", 
                                     "DRAWING", "PAUSED", "COMPLETED", "ERROR", "EMERGENCY"};
  return (status < 13) ? statusNames[status] : "UNKNOWN";
}

void LEDManager::setStatus(LEDStatus status) {
  if (currentStatus != status) {
    currentStatus = status;
    lastUpdate = millis();
    ledState = false;
    breathValue = 0;
    breathDirection = true;
  }
}

void LEDManager::setProgress(float progress) {
  if (currentStatus == LED_DRAWING) {
    setProgressBar(progress, colorDrawing);
  }
}

void LEDManager::setCustomColor(LEDColor color, uint8_t brightness) {
  setStripColor(color, brightness);
  digitalWrite(statusLedPin, brightness > 128 ? HIGH : LOW);
}

void LEDManager::clear() {
  if (strip) {
    strip->clear();
    strip->show();
  }
  digitalWrite(statusLedPin, LOW);
}

void LEDManager::test() {
  Serial.println("💡 LED测试开始...");
  
  // 测试状态LED
  for (int i = 0; i < 3; i++) {
    digitalWrite(statusLedPin, HIGH);
    delay(300);
    digitalWrite(statusLedPin, LOW);
    delay(300);
  }
  
  // 测试WS2812灯带
  if (strip) {
    // 红色
    setStripColor(LEDColor(255, 0, 0));
    delay(500);
    
    // 绿色
    setStripColor(LEDColor(0, 255, 0));
    delay(500);
    
    // 蓝色
    setStripColor(LEDColor(0, 0, 255));
    delay(500);
    
    // 白色
    setStripColor(LEDColor(255, 255, 255));
    delay(500);
    
    // 清除
    clear();
  }
  
  Serial.println("💡 LED测试完成");
}

void LEDManager::setLedCount(uint16_t count) {
  if (count != numLeds) {
    numLeds = count;
    
    // 重新分配火焰效果数组
    if (fireHeat) {
      delete[] fireHeat;
    }
    if (numLeds > 0) {
      fireHeat = new uint8_t[numLeds];
      for (int i = 0; i < numLeds; i++) {
        fireHeat[i] = 0;
      }
    } else {
      fireHeat = nullptr;
    }
    
    // 重新初始化WS2812
    if (strip && ws2812Enabled) {
      delete strip;
      strip = new Adafruit_NeoPixel(numLeds, ws2812Pin, NEO_GRB + NEO_KHZ800);
      strip->begin();
      strip->setBrightness(globalBrightness);
      strip->clear();
      strip->show();
    }
    
    Serial.printf("💡 WS2812灯珠数量已更新为: %d\n", numLeds);
  }
}

// ==================== 功能开关控制 ====================

void LEDManager::enableWS2812(bool enable) {
  if (ws2812Enabled != enable) {
    ws2812Enabled = enable;
    
    if (enable) {
      if (!strip) {
        strip = new Adafruit_NeoPixel(numLeds, ws2812Pin, NEO_GRB + NEO_KHZ800);
        strip->begin();
        strip->setBrightness(globalBrightness);
        strip->clear();
        strip->show();
      }
      Serial.println("💡 WS2812灯带已启用");
    } else {
      if (strip) {
        strip->clear();
        strip->show();
        // 🔧 修复：禁用时不释放内存，保持strip对象用于重新启用
        // 避免频繁的内存分配和释放
      }
      Serial.println("💡 WS2812灯带已禁用");
    }
  }
}

void LEDManager::enableStatusLed(bool enable) {
  if (statusLedEnabled != enable) {
    statusLedEnabled = enable;
    
    if (enable) {
      pinMode(statusLedPin, OUTPUT);
      Serial.println("💡 状态LED已启用");
    } else {
      digitalWrite(statusLedPin, LOW);
      Serial.println("💡 状态LED已禁用");
    }
  }
}

void LEDManager::setEffectMode(LEDEffectMode mode) {
  currentEffect = mode;
  Serial.printf("💡 效果模式切换为: %d\n", mode);
}



// ==================== 私有方法实现 ====================

void LEDManager::setStripColor(LEDColor color, uint8_t brightness) {
  if (!strip) return;
  
  uint8_t r = (color.r * brightness) / 255;
  uint8_t g = (color.g * brightness) / 255;
  uint8_t b = (color.b * brightness) / 255;
  
  for (uint16_t i = 0; i < numLeds; i++) {
    strip->setPixelColor(i, strip->Color(r, g, b));
  }
  strip->show();
}

void LEDManager::setStripRange(int start, int end, LEDColor color, uint8_t brightness) {
  if (!strip) return;
  
  uint8_t r = (color.r * brightness) / 255;
  uint8_t g = (color.g * brightness) / 255;
  uint8_t b = (color.b * brightness) / 255;
  
  for (int i = start; i <= end && i < numLeds; i++) {
    strip->setPixelColor(i, strip->Color(r, g, b));
  }
  strip->show();
}

void LEDManager::setProgressBar(float progress, LEDColor color) {
  if (!strip) return;
  
  // 限制进度范围
  progress = constrain(progress, 0.0, 1.0);
  
  int progressLeds = (int)(progress * numLeds);
  
  // 清除所有LED
  strip->clear();
  
  // 设置进度条
  for (int i = 0; i < progressLeds; i++) {
    uint8_t brightness = 150;
    if (i == progressLeds - 1) {
      // 最后一个LED闪烁表示当前进度
      brightness = (millis() % 1000 < 500) ? 255 : 50;
    }
    uint8_t r = (color.r * brightness) / 255;
    uint8_t g = (color.g * brightness) / 255;
    uint8_t b = (color.b * brightness) / 255;
    strip->setPixelColor(i, strip->Color(r, g, b));
  }
  
  strip->show();
}

void LEDManager::breathEffect(LEDColor color) {
  unsigned long currentTime = millis();
  static unsigned long lastBreathUpdate = 0;  // 🔧 修复：使用独立的时序变量避免与其他效果冲突
  
  if (currentTime - lastBreathUpdate > 20) {  // 50Hz更新频率
    if (breathDirection) {
      breathValue += 5;
      if (breathValue >= 255) {
        breathValue = 255;
        breathDirection = false;
      }
    } else {
      breathValue -= 5;
      if (breathValue <= 50) {
        breathValue = 50;
        breathDirection = true;
      }
    }
    
    setStripColor(color, breathValue);
    if (statusLedEnabled) digitalWrite(statusLedPin, breathValue > 128 ? HIGH : LOW);
    
    lastBreathUpdate = currentTime;
  }
}

void LEDManager::blinkEffect(LEDColor color, unsigned long interval) {
  unsigned long currentTime = millis();
  static unsigned long lastBlinkUpdate = 0;  // 🔧 修复：使用独立的时序变量
  
  if (currentTime - lastBlinkUpdate > interval) {
    ledState = !ledState;
    
    if (statusLedEnabled) digitalWrite(statusLedPin, ledState);
    if (ws2812Enabled) setStripColor(color, ledState ? globalBrightness : 0);
    
    lastBlinkUpdate = currentTime;
  }
}

void LEDManager::solidEffect(LEDColor color) {
  setStripColor(color, globalBrightness);
}

// ==================== 炫酷效果实现 ====================

void LEDManager::rainbowEffect() {
  if (!strip) return;
  
  unsigned long currentTime = millis();
  static unsigned long lastRainbowUpdate = 0;  // 🔧 修复：独立时序变量
  if (currentTime - lastRainbowUpdate > 50) {  // 20Hz更新频率
    for (uint16_t i = 0; i < numLeds; i++) {
      uint16_t pixelHue = rainbowOffset + (i * 65536L / numLeds);
      strip->setPixelColor(i, strip->gamma32(strip->ColorHSV(pixelHue)));
    }
    strip->show();
    
    rainbowOffset += 512;  // 彩虹滚动速度
    lastRainbowUpdate = currentTime;
  }
}

void LEDManager::fireEffect() {
  if (!strip || !fireHeat) return;
  
  unsigned long currentTime = millis();
  static unsigned long lastFireUpdate = 0;  // 🔧 修复：独立时序变量
  if (currentTime - lastFireUpdate > 80) {  // 12.5Hz更新频率
    // 第一步：降温每个LED
    for (int i = 0; i < numLeds; i++) {
      int coolingValue = (int)random(0, ((55 * 10) / numLeds) + 2);
      fireHeat[i] = max(0, (int)fireHeat[i] - coolingValue);
    }
    
    // 第二步：热量从每个LED向上传播
    for (int k = numLeds - 1; k >= 2; k--) {
      fireHeat[k] = (fireHeat[k - 1] + fireHeat[k - 2] + fireHeat[k - 2]) / 3;
    }
    
    // 第三步：在底部随机产生新的火花
    if ((int)random(255) < 120) {
      int y = (int)random(7);
      int sparkValue = (int)random(160, 255);
      fireHeat[y] = min(255, (int)fireHeat[y] + sparkValue);
    }
    
    // 第四步：将热量映射为颜色
    for (int j = 0; j < numLeds; j++) {
      LEDColor fireColor = heatColor(fireHeat[j]);
      strip->setPixelColor(j, strip->Color(fireColor.r, fireColor.g, fireColor.b));
    }
    
    strip->show();
    lastFireUpdate = currentTime;
  }
}

void LEDManager::waveEffect(LEDColor color) {
  if (!strip) return;
  
  unsigned long currentTime = millis();
  if (currentTime - lastUpdate > 50) {  // 20Hz更新频率
    for (uint16_t i = 0; i < numLeds; i++) {
      float wave = sin((i + (currentTime / 100.0)) * 0.5) * 0.5 + 0.5;
      uint8_t brightness = (uint8_t)(wave * globalBrightness);
      
      uint8_t r = (color.r * brightness) / 255;
      uint8_t g = (color.g * brightness) / 255;
      uint8_t b = (color.b * brightness) / 255;
      
      strip->setPixelColor(i, strip->Color(r, g, b));
    }
    strip->show();
    lastUpdate = currentTime;
  }
}

void LEDManager::meteorEffect(LEDColor color) {
  if (!strip) return;
  
  unsigned long currentTime = millis();
  if (currentTime - lastUpdate > 100) {  // 10Hz更新频率 - 直接采用附件方案
    // 衰减所有LED
    for (int i = 0; i < numLeds; i++) {
      fadeToBlack(i, 64);
    }
    
    // 绘制流星
    for (int j = 0; j < 10; j++) {  // 流星尾巴长度
      if ((meteorPos - j < numLeds) && (meteorPos - j >= 0)) {
        uint8_t brightness = globalBrightness - (j * 20);
        if (brightness < 20) brightness = 20;
        
        uint8_t r = (color.r * brightness) / 255;
        uint8_t g = (color.g * brightness) / 255;
        uint8_t b = (color.b * brightness) / 255;
        
        strip->setPixelColor(meteorPos - j, strip->Color(r, g, b));
      }
    }
    
    strip->show();
    
    meteorPos++;
    if (meteorPos >= numLeds + 10) {
      meteorPos = 0;
    }
    
    lastUpdate = currentTime;
  }
}

void LEDManager::sparkleEffect(LEDColor color) {
  if (!strip) return;
  
  unsigned long currentTime = millis();
  if (currentTime - lastUpdate > 100) {  // 10Hz更新频率
    // 随机闪烁几个LED
    strip->clear();
    
    for (int i = 0; i < numLeds / 10; i++) {  // 约10%的LED闪烁
      int pixel = (int)random(numLeds);
      uint8_t brightness = (uint8_t)random(100, 255);
      
      uint8_t r = (color.r * brightness) / 255;
      uint8_t g = (color.g * brightness) / 255;
      uint8_t b = (color.b * brightness) / 255;
      
      strip->setPixelColor(pixel, strip->Color(r, g, b));
    }
    
    strip->show();
    lastUpdate = currentTime;
  }
}

void LEDManager::theaterChaseEffect(LEDColor color) {
  if (!strip) return;
  
  unsigned long currentTime = millis();
  if (currentTime - lastUpdate > 200) {  // 5Hz更新频率
    strip->clear();
    
    for (int i = theaterStep; i < numLeds; i += 3) {
      uint8_t r = (color.r * globalBrightness) / 255;
      uint8_t g = (color.g * globalBrightness) / 255;
      uint8_t b = (color.b * globalBrightness) / 255;
      
      strip->setPixelColor(i, strip->Color(r, g, b));
    }
    
    strip->show();
    
    theaterStep = (theaterStep + 1) % 3;
    lastUpdate = currentTime;
  }
}

// ==================== 极坐标追踪效果 ====================

void LEDManager::setPolarPosition(float theta, float rho) {
  currentTheta = theta;
  currentRho = rho;
}

void LEDManager::polarTrackEffect(LEDColor color) {
  if (!strip) return;
  
  // 清除所有LED
  strip->clear();
  
  // 角度归一化到0-2π范围
  float normalizedTheta = fmod(currentTheta, 2 * PI);
  if (normalizedTheta < 0) {
    normalizedTheta += 2 * PI;
  }
  
  // 将角度映射到LED索引 (0度对应第0个LED，360度对应最后一个LED)
  // 注意：LED环形排列，第一个LED在0度位置
  int centerLedIndex = (int)((normalizedTheta / (2 * PI)) * numLeds) % numLeds;
  
  // 根据半径计算要点亮的LED数量
  // 半径0时：点亮总数的1/4 (25%)
  // 半径1时：点亮总数的1/32 (约3.1%)
  // 线性关系：亮灯数 = 总数 * (0.25 - 0.21875 * rho)
  float lightRatio = 0.25f - 0.21875f * currentRho;  // 0.25 -> 0.03125
  int numLightsToShow = max(1, (int)(numLeds * lightRatio));
  
  // 确保亮灯数不超过总LED数
  numLightsToShow = min(numLightsToShow, (int)numLeds);
  
  // 计算亮灯范围（以centerLedIndex为中心，向两边扩展）
  int halfRange = numLightsToShow / 2;
  
  // 点亮LED
  for (int i = 0; i < numLightsToShow; i++) {
    int ledIndex;
    
    if (numLightsToShow % 2 == 1) {
      // 奇数个LED：中心LED + 左右对称
      ledIndex = (centerLedIndex - halfRange + i + numLeds) % numLeds;
    } else {
      // 偶数个LED：左右对称，无明确中心
      ledIndex = (centerLedIndex - halfRange + i + numLeds) % numLeds;
    }
    
    // 计算亮度渐变效果（中心最亮，边缘较暗）
    int distanceFromCenter = abs(i - halfRange);
    float brightnessFactor = 1.0f - (float)distanceFromCenter / (float)(halfRange + 1);
    brightnessFactor = max(0.3f, brightnessFactor);  // 最低亮度30%
    
    // 使用绘图专用亮度
    uint8_t adjustedBrightness = (uint8_t)(drawingBrightness * brightnessFactor);
    uint8_t r = (color.r * adjustedBrightness) / 255;
    uint8_t g = (color.g * adjustedBrightness) / 255;
    uint8_t b = (color.b * adjustedBrightness) / 255;
    
    strip->setPixelColor(ledIndex, strip->Color(r, g, b));
  }
  
  strip->show();
  
  // 调试信息（每50次更新输出一次，避免日志过多）
  
}

// ==================== 辅助方法 ====================

uint32_t LEDManager::wheel(byte wheelPos) {
  wheelPos = 255 - wheelPos;
  if (wheelPos < 85) {
    return strip->Color(255 - wheelPos * 3, 0, wheelPos * 3);
  }
  if (wheelPos < 170) {
    wheelPos -= 85;
    return strip->Color(0, wheelPos * 3, 255 - wheelPos * 3);
  }
  wheelPos -= 170;
  return strip->Color(wheelPos * 3, 255 - wheelPos * 3, 0);
}

LEDColor LEDManager::heatColor(uint8_t heat) {
  LEDColor result;
  
  // 根据热量值计算火焰颜色
  uint8_t t192 = (heat * 192) / 255;  // 0-192范围
  uint8_t heatramp = t192 & 0x3F;     // 0-63范围
  heatramp <<= 2;                     // 0-252范围
  
  if (t192 & 0x80) {
    // 最热的三分之一：从红色到白色
    result.r = 255;
    result.g = 255;
    result.b = heatramp;
  } else if (t192 & 0x40) {
    // 中等热度：从黑色到红色
    result.r = 255;
    result.g = heatramp;
    result.b = 0;
  } else {
    // 最冷的三分之一：从黑色到红色
    result.r = heatramp;
    result.g = 0;
    result.b = 0;
  }
  
  return result;
}

void LEDManager::fadeToBlack(int ledNo, byte fadeValue) {
  if (!strip || ledNo >= numLeds) return;
  
  uint32_t oldColor = strip->getPixelColor(ledNo);
  uint8_t r = (oldColor >> 16) & 0xFF;
  uint8_t g = (oldColor >> 8) & 0xFF;
  uint8_t b = oldColor & 0xFF;
  
  r = (r <= 10) ? 0 : (int)r - (r * fadeValue / 256);
  g = (g <= 10) ? 0 : (int)g - (g * fadeValue / 256);
  b = (b <= 10) ? 0 : (int)b - (b * fadeValue / 256);
  
  strip->setPixelColor(ledNo, strip->Color(r, g, b));
}

// ==================== 临时颜色提示功能 ====================

void LEDManager::setTemporaryColor(LEDColor color, uint8_t brightness) {
  temporaryColorActive = true;
  temporaryColor = color;
  temporaryBrightness = brightness;
  
  // 触发更新显示（通过update()统一处理）
  update();
}

void LEDManager::clearTemporaryColor() {
  temporaryColorActive = false;
  
  // 恢复正常状态显示
  update();
}

// ==================== 安全检查和故障恢复方法 ====================

bool LEDManager::isWS2812Healthy() {
  // 检查WS2812是否正常工作
  return strip != nullptr && ws2812Enabled;
}

void LEDManager::resetWS2812() {
  // 重置WS2812灯带到安全状态
  if (strip) {
    Serial.println("🔧 重置WS2812灯带...");
    strip->clear();
    strip->show();
    delay(100);
    
    // 重新初始化
    strip->setBrightness(globalBrightness);
    strip->clear();
    strip->show();
    
    Serial.println("✅ WS2812灯带重置完成");
  }
}

void LEDManager::safeShutdown() {
  // 安全关闭所有LED
  Serial.println("🛡️ LED管理器安全关闭...");
  
  // 清除临时状态
  temporaryColorActive = false;
  drawingSessionActive = false;
  
  // 关闭状态LED
  if (statusLedEnabled) {
    digitalWrite(statusLedPin, LOW);
  }
  
  // 清除并禁用WS2812
  if (strip && ws2812Enabled) {
    strip->clear();
    strip->show();
  }
  
  currentStatus = LED_OFF;
  Serial.println("✅ LED管理器安全关闭完成");
}

// =============== 业务逻辑已移至 LEDControlCenter ===============
// LEDManager 现在是纯硬件驱动层，只响应 setStatus() 等硬件命令

void LEDManager::updatePosition(float theta, float rho) {
  // 更新当前位置（按照附件验证方案）
  currentTheta = theta;
  currentRho = rho;
  
  // 静态变量用于控制更新频率，避免过于频繁的位置更新
  static unsigned long lastPositionUpdate = 0;
  unsigned long currentTime = millis();
  
  // 每50ms更新一次位置（20Hz），足够流畅且不会过载
  if (currentTime - lastPositionUpdate >= 50) {
    lastPositionUpdate = currentTime;
    // 这里可以添加基于位置的LED效果，比如极坐标追踪效果
  }
}
